package com.japanesee_learning.until;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class ImagesUntil {

	private static final String TAG = ImagesUntil.class.getSimpleName();
	public static Context mContext;

	public ImagesUntil() {
	}

	public ImagesUntil(Context _context) {
		mContext = _context;
	}

	/**
	 * decodes image and scales it to reduce memory consumption
	 * **/
	public Bitmap getBitmap(Uri path) {

		Uri uri = path;
		InputStream in = null;
		try {
			final int IMAGE_MAX_SIZE = 1500000; // 1.5MP
			ContentResolver mContentResolver = mContext.getContentResolver();
			in = mContentResolver.openInputStream(uri);

			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(in, null, o);
			in.close();

			int scale = 1;
			while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) {
				scale++;
			}
			Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth
					+ ", orig-height: " + o.outHeight);

			Bitmap b = null;
			in = mContentResolver.openInputStream(uri);
			if (scale > 1) {
				scale--;
				// scale to max possible inSampleSize that still yields an image
				// larger than target
				o = new BitmapFactory.Options();
				o.inSampleSize = scale;
				b = BitmapFactory.decodeStream(in, null, o);

				// resize to desired dimensions
				int height = b.getHeight();
				int width = b.getWidth();
				Log.d(TAG, "1th scale operation dimenions - width: " + width
						+ ",height: " + height);

				double y = Math.sqrt(IMAGE_MAX_SIZE
						/ (((double) width) / height));
				double x = (y / height) * width;

				Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
						(int) y, true);
				b.recycle();
				b = scaledBitmap;

				System.gc();
			} else {
				b = BitmapFactory.decodeStream(in);
			}
			in.close();

			Log.d(TAG, "bitmap size - width: " + b.getWidth() + ", height: "
					+ b.getHeight());
			return b;
		} catch (IOException e) {
			Log.e(TAG, e.getMessage(), e);
			return null;
		}
	}

	/**
	 * Get ratation of image
	 * **/
	public int getOrientation(Uri selectedImage) {
		int orientation = 0;
		final String[] projection = new String[] { MediaStore.Images.Media.ORIENTATION };
		final Cursor cursor = mContext.getContentResolver().query(
				selectedImage, projection, null, null, null);
		if (cursor != null) {
			final int orientationColumnIndex = cursor
					.getColumnIndex(MediaStore.Images.Media.ORIENTATION);
			if (cursor.moveToFirst()) {
				orientation = cursor.isNull(orientationColumnIndex) ? 0
						: cursor.getInt(orientationColumnIndex);
			}
			cursor.close();
		}
		return orientation;
	}

	/**
	 * Android image rounded corners
	 * **/
	public static Bitmap setRoundCorner(Bitmap src, float round) {

		// image size
		int width = src.getWidth();
		int height = src.getHeight();

		// config rectangle for embedding
		final Rect rect = new Rect(0, 0, width, height);
		final RectF rectF = new RectF(rect);

		// create bitmap output
		Bitmap result = Bitmap.createBitmap(width, height, Config.ARGB_8888);

		// set canvas for painting
		Canvas canvas = new Canvas(result);
		canvas.drawARGB(0, 0, 0, 0);

		// config paint
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setColor(0xff424242);

		paint.setColor(Color.BLACK);

		// draw rect to canvas
		canvas.drawRoundRect(rectF, round, round, paint);

		// create Xfer mode
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);

		// draw source image to canvas
		canvas.drawBitmap(src, rect, rect, paint);

		// return final image
		return result;
	}
	
	/**
	 * Draw shadow for  bitmap
	 * **/
	public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
	    int w = bitmap.getWidth();
	    int h = bitmap.getHeight();

	    int newW = w - (leftRightThk * 2);
	    int newH = h - (bottomThk + padTop);

	    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
	    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
	    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

	    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
	    Canvas c = new Canvas(bmp);

	    // Left
	    int leftMargin = (leftRightThk + 7)/2;
	    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
	    paint.setShader(lshader);
	    c.drawRect(0, padTop, leftMargin, newH, paint); 

	    // Right
	    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
	    paint.setShader(rshader);
	    c.drawRect(newW, padTop, w, newH, paint);

	    // Bottom
	    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
	    paint.setShader(bshader);
	    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
	    c.drawBitmap(sbmp, leftRightThk, 0, null);

	    return bmp;
	}

	/**
	 * Function set border for imageview
	 * **/
	public static Bitmap setBorder(Bitmap _bitmap) {
		int width = _bitmap.getWidth();
		int height = _bitmap.getHeight();

		// create bitmap output
		Bitmap result = Bitmap.createBitmap(width, height, Config.ARGB_8888);


		// return final image
		return result;
	}

	/**
	 * Delete an image from sdcard
	 * **/
	public void deleteImage(String _path) {
		File direct = new File(_path);
		Log.v(TAG, "Path delete: " + _path);
		if (direct.exists()) {
			direct.delete();
		} else {
			Log.v(TAG, "Error deleting image: Path not exists : " + _path);
		}
	}
}
